// 数据库架构更新脚本
const { getPool } = require('../database');

async function updateDatabaseSchema() {
  try {
    console.log('开始更新数据库架构...');
    const pool = getPool();
    
    // 1. 检查api_keys表是否存在
    const [tables] = await pool.query('SHOW TABLES LIKE ?', ['api_keys']);
    if (tables.length === 0) {
      console.log('api_keys表不存在，将创建表');
      await pool.query(`
        CREATE TABLE IF NOT EXISTS api_keys (
          id INT AUTO_INCREMENT PRIMARY KEY,
          \`key\` TEXT NOT NULL,
          provider VARCHAR(50) NOT NULL,
          endpoint VARCHAR(255) NOT NULL,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      console.log('api_keys表创建成功');
    } else {
      console.log('api_keys表已存在，将更新结构');
      
      // 2. 更新key字段类型为TEXT
      try {
        console.log('修改key字段类型为TEXT...');
        await pool.query(`
          ALTER TABLE api_keys 
          MODIFY COLUMN \`key\` TEXT NOT NULL
        `);
        console.log('key字段类型修改成功');
      } catch (error) {
        console.error('修改字段类型时出错:', error.message);
      }
      
      // 3. 检查是否需要添加modelName字段
      try {
        console.log('检查modelName字段是否存在...');
        const [columns] = await pool.query(`SHOW COLUMNS FROM api_keys LIKE 'modelName'`);
        
        if (columns.length === 0) {
          console.log('添加modelName字段...');
          await pool.query(`
            ALTER TABLE api_keys 
            ADD COLUMN modelName VARCHAR(100) DEFAULT NULL AFTER endpoint
          `);
          console.log('modelName字段添加成功');
        } else {
          console.log('modelName字段已存在');
        }
      } catch (error) {
        console.error('检查或添加modelName字段时出错:', error.message);
      }
    }
    
    console.log('数据库架构更新完成');
    process.exit(0);
  } catch (error) {
    console.error('更新数据库架构时出错:', error);
    process.exit(1);
  }
}

// 执行更新
updateDatabaseSchema(); 